import { message } from "antd";

const baseUrl = '/api';

export default function request(url, options = {}) {
    // const { body, query } = options;
    const { body, query, ...rest } = options;
    // let fetchParams = {
    //     ...rest
    // };
    if (options.body) {
        let body = options.body || {};
        let s = "";
        Object.keys(body).forEach(key => {
            console.log('body=======>', body);
            console.log('key=======>', key);
            if (body[key] == undefined || body[key] == '') return;
            s += `${key}=${body[key]}&`
        })
        options.body = s
        // fetchParams.body = s
    }
    if (options.query) {
        const query = options.query || {};
        let s = '';
        Object.keys(query).forEach(key => {
            if (query[key] == undefined || query[key] == '') return;
            s += `${key}=${query[key]}&`
        })
        url = `${url}?${s}`;
    }

    options.headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
        "Authentication": localStorage.getItem('token')
    }

    return fetch(baseUrl + url,options).then(response=>{
    // return fetch(baseUrl + url,options).then(response=>{
        console.log('response',response);
        switch(response.status){
            case 200:
                return response.json();
            case 401:
                localStorage.clear();
                window.location.pathname = 'login';
                break;
            case 403:
                message.error("对不起，您没有权限访问该接口");
                return Promise.reject(response.json());
            default:
                return Promise.reject(response.json())
        }
    }).catch(err=>{
        console.log('error',err);
        const msg = "Unexpected end of JSON input";
        if (err.message && err.message == msg) {
            return Promise.resolve();
        }
        return Promise.reject(err);
    })
}